package com.xunhang.utils;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.xunhang.dto.AdminDTO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import static com.xunhang.utils.Constants.SECRETT_CODE;
import static com.xunhang.utils.Constants.TOKEN_KEY;

@AllArgsConstructor
public class JWTInterceptor implements HandlerInterceptor {
    private final StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token=request.getHeader("authorization");
        if(token==null){
            return true;
        }

        if(JWTUtil.verify(token,SECRETT_CODE.getBytes())){
            String key=TOKEN_KEY+token;
            if(stringRedisTemplate.opsForValue().get(key)!=null){;
                AdminDTO admin= JWT.of(token).getPayloads().toBean(AdminDTO.class);
                AdminHolder.saveToken(token);
                AdminHolder.saveAdmin(admin);
            }
        }
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AdminHolder.removeToken();
        AdminHolder.removeAdmin();
    }
}
